<template>
  <div class="app-container">
    <nabtwo index="0" :params="param"></nabtwo>
    <friend style="margin-bottom: 20px;" :indexCount="indexCount"></friend>
    
    <el-form :model="queryParams" class="frominfo" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <div class="from-item">
        <el-form-item label="微信名称" prop="wcUserName">
          <el-input v-model="queryParams.wcUserName" @keyup.enter.native="handleQuery" placeholder="请输入微信名称" clearable/>
        </el-form-item>
        <el-form-item label="微信备注" prop="wcNoteName">
          <el-input v-model="queryParams.wcNoteName" @keyup.enter.native="handleQuery" placeholder="请输入微信备注" clearable/>
        </el-form-item>
        <el-form-item label="聊天时间" prop="lastChatTime">
          <el-date-picker v-model="chatTime" style="width: 240px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="标签" prop="labelName">
          <el-select v-model="labelName" multiple placeholder="请选择标签">
              <el-option
                v-for="item in friendInfo"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictLabel">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否在网" prop="interState">
          <el-select v-model="queryParams.interState" placeholder="请选择" clearable>
            <el-option v-for="dict in dict.type.sys_network_status" :key="dict.value" :label="dict.label" :value="dict.value"/>
          </el-select>
        </el-form-item>
      </div>
      <div class="from-Btn">
        <el-form-item>
            <el-button class="blue-button" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button class="blue-button" plain icon="el-icon-folder-add" size="mini"  @click="handleUpdate" v-hasPermi="['arbit:wcfriendinfo:edit']">批量标签</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button class="blue-button" plain icon="el-icon-upload2" size="mini" @click="handleExport" v-hasPermi="['arbit:wcfriendinfo:export']">批量导出</el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>

    <el-table v-loading="loading" :data="wcFriendInfoList" :header-cell-style="{ background: '#fcfcfd', color: '#000' }" @selection-change="handleSelectionChange"  @select-all="handleSelectAll" :border="false">
      <el-table-column label="全选" type="selection" width="55" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="微信名称" prop="wcUserName" align="center" :show-overflow-tooltip="true"/>
      <!-- <el-table-column label="好友微信号" prop="wcUserNumber" align="center" :show-overflow-tooltip="true"/> -->
      <el-table-column label="微信备注" prop="wcNoteName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="是否在网" prop="interState" align="center" :show-overflow-tooltip="true">
        <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_network_status" :value="scope.row.interState"/>
        </template>
      </el-table-column>
      <el-table-column label="标签" prop="friendLabel" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="微信所属人员" prop="userName" align="center" :show-overflow-tooltip="true"/>
      <el-table-column label="最近聊天时间" prop="lastChatTime" align="center" :show-overflow-tooltip="true" width="180">
          <template slot-scope="scope">
              <span>{{ parseTime(scope.row.lastChatTime, '{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
      </el-table-column>
      <el-table-column align="center" width="120" class-name="small-padding fixed-width" v-if="checkPermi(['massage:massage:getMags'])">
        <template slot="header">
          <span>聊天详情</span>
          <el-tooltip class="item" effect="dark" content="进入操作各个微信号" placement="top">
            <i class="el-icon-warning" style="color:#818e96;"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
           <span style="cursor: pointer;color:#0078fb" @click="golink(scope.row.wcUserId,scope.row.wcId,scope.row.wcName,scope.row.wcUserName)">详情</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

   
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import request from '@/utils/request'
import mathNum from "../../components/daily.js"
import nabtwo from '../../components/nabtwo.vue'
import friend from '../../components/friend.vue'
import { checkPermi } from "@/utils/permission"; // 权限判断函数
export default {
  name: "WcFriendInfo",
  dicts: ['sys_network_status'],
  components:{
    nabtwo,
    friend,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      selectAll:false,
      selection:[],
      chatTime:[],
      // 微信好友信息表格数据
      wcFriendInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      param:{wxid:this.$route.query.wxid,userid:this.$route.query.userid},
      labelName:[],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wcId: null,
        wcUserName: null,
        wcNoteName: null,
        wcUserRegion: null,
        friendLabel:null,
        interState: null,
        beginTime: null,
        endTime: null,
      },
      indexCount:[{ name: '今日新增好友', num: 0, type: 0, bili:0}, { name: '今日新入网', num: 0, type: 0, bili: 0 }],
      lable:[],
      friendInfo:[],
    };
  },
  created() {
  },
  mounted(){
    this.queryParams.wcId = this.$route.query.wxid;
    this.getList();
    //this.getLable();
    this.friendLabel()
    this.init()
  },
  methods: {
    init(){
      getUserInternet({wcId:this.$route.query.wxid}).then(res => {
          //console.log(res)
          if(res.code==200){
              if(res.data){
                this.indexCount[1].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
                this.indexCount[1].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
                this.indexCount[1].num=res.data.new_size
              }
          }
      })
      getAddFriend({wcId:this.$route.query.wxid}).then(res => {
          //console.log(res)
          if(res.code==200){
              if(res.data){
                this.indexCount[0].type=mathNum(res.data.new_size,res.data.old_size).split('_')[0]
                this.indexCount[0].bili=mathNum(res.data.new_size,res.data.old_size).split('_')[1]
                this.indexCount[0].num=res.data.new_size
              }
          }
      })
    },
    checkPermi,
    getLable(){
      getLableInfo().then(res=>{
        //console.log(res)
        if(res.code==200){
          this.lable=res.data.map(item => {
            return item.lableName
          })
        }
      })
    },
    friendLabel(){
        friendLabel().then(res => {
          //console.log(res)
          if(res.code==200){
            this.friendInfo=res.data
          }
        });
    },
    golink(userid,wxid,name,username){
      this.$router.push({ path:"/market/detial/index/",name:'frienddetial',query: { userid,wxid,name,username}}).catch(()=>{});
    },
    /** 查询微信好友信息列表 */
    getList() {
      this.loading = true;
      var lable=""
      if(this.labelName!=null){
          this.labelName.forEach(element => {
            lable+=","+element
          })
      }
      this.queryParams.friendLabel=lable.substring(1)
      listWcFriendInfo(this.queryParams).then(res => {
        if (res['success']) {
          const dt = res['data'];
          this.total = dt['total'];
          this.wcFriendInfoList = dt['records'];
        }
        this.loading = false;
      });
    },
    handleUpdate(){
      if(this.ids!=''){
        this.open = true;
      }else{
        this.$message({
            message: '请选择！',
            type: 'warning'
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.beginTime=null
      this.queryParams.endTime=null
      if(this.chatTime!=''&&this.chatTime!=null){
        this.queryParams.beginTime=this.chatTime[0]+' 00:00:00'
        this.queryParams.endTime=this.chatTime[1]+' 23:59:59'
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime=[]
      this.labelName=[]
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //console.log(selection)
      this.selectAll=false
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
      this.selection=selection
    },
    handleSelectAll(selection){
      this.selectAll=false
      if(selection!=''){
          this.ids=selection.map(item => item.id)
          this.selectAll=true
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      if(this.ids==''){
        this.$message({
            message: '请选择要导出的数据！',
            type: 'warning'
        });
        return
      }
      if(this.selectAll){
        this.download('arbit/wcfriend_info/export', {
           ...this.queryParams
        }, `wcFriendInfo_${new Date().getTime()}.xlsx`)
      }else{
          this.exportExcel()
      }
     
    },
    exportExcel() {
      const data = [["id","微信名称", "微信备注", "是否在网","标签", "微信所属人员", "最近聊天时间"],];
      this.selection.forEach(element => {
        var arr=[element.id,element.wcUserName,element.wcNoteName,element.interState==0?'离线':'在线',element.lableName,element.wcUserName,element.lastChatTime]
        data.push(arr)
      });
      
      // 将数据转换为工作表
      const ws = XLSX.utils.aoa_to_sheet(data);
 
      // 创建工作簿并添加工作表
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
 
      // 生成Excel文件
      const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
 
      // 字符串转ArrayBuffer
      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
        return buf;
      }
 
      // 保存文件
      saveAs(new Blob([s2ab(wbout)], { type: 'application/octet-stream' }), `friend_${new Date().getTime()}.xlsx`);
    },
    
  }
};

/** js请求 调用 */

// 查询微信好友信息列表
export function listWcFriendInfo(query) {
  return request({
    url: '/arbit/wcfriend_info/page',
    method: 'get',
    params: query
  })
}

  // 获取今日新增好友数量
  export function getAddFriend(data) {
    return request({
      url: '/arbit/wcfriend_info/new_friend',
      method: 'get',
      data: data
    })
  }
  
  // 获取好友在网数量
  export function getUserInternet(data) {
    return request({
      url: '/arbit/wcfriend_info/data_friend_olin',
      method: 'get',
      data:data
    })
  }
  // 获取微信标签信息
  export function getLableInfo() {
    return request({
      url: '/wxassistant/wcuser_lable_copy/pagex',
      method: 'get',
    })
  }
  //获取所有好友标签
  export function friendLabel() {
    return request({
      url: '/label/relevance/type/friend_label',
      method: 'GET',
    })
  }
</script>
<style scoped lang="scss">
  .app-container{
    background-color: #f6f9fb;
  }
  .frominfo{
    display: flex;background-color: #fff;padding: 10px;padding-bottom: 0; margin-bottom: 20px;
    .from-item{
      display: flex;flex-wrap: wrap;
    }
    .from-Btn{
      display: flex;flex-direction: column;align-items: center;justify-content: center;width: 20%;
    }
  }
  .mb8{
    margin-bottom: 20px;
  }
  .blue-button {
    color: #fff;
    background-color: #0078fb;
    border-color: #0078fb;
  }
</style>
